"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008  Obol Software Pty Ltd

This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt

"""

from mod_python import apache
from mod_python import Session
from mod_python import util

from phunc import *
import phunc.cx_wrapper.db_tools as db_tools
from phunc.logger import logger

# legacy namespacing
GeneralBusinessErr = exception.GeneralBusinessErr
genErrorPage = error.genErrorPage

def index(req, **params):
	"""displays a form for setting up account ranges on one of the financial reports"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	max_id = db_tools.exec_action(dbc,'get_max_id',[params['report_id']])
	report_menu_items = [params['report_id']==str(key) and value or value[:-1] for key,value in {1:'balsheet!',2:'pl!',3:'taxreport!'}.iteritems()]
	page.content = {
		'report_detail':db_tools.exec_action(dbc,'get_report_detail',[int(params['report_id'])]),
		'report_info':db_tools.exec_action(dbc,'get_report_info',[int(params['report_id'])])[0],
		'max_id':max_id[0]['max_id'] or '10'
	}
	page.setup = {
		'breadcrumbs':['finance',page.content['report_info']['name'].replace('&','&amp;')],
		'menu_title':'General Ledger',
		'menu':['recordexp', 'spacer', 'account', 'special','linked','subledger', 'spacer', 'journal', 'editjournal', 'postjournal','spacer'] + report_menu_items,
		'content_title':page.content['report_info']['name'].replace('&','&amp;'),
		'template':'report/create_report.opt',
		'form':True,
		'javascript':True
	}
	page.info = {
		'query_string':info.query_string,
	}
	return page.render()
		
def add_item_page(req, **params):
	"""displays a form for adding a line item to one of the reports"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	report_menu_items = [params['report_id']==str(key) and value or value[:-1] for key,value in {1:'balsheet!',2:'pl!',3:'taxreport!'}.iteritems()]
	page.content = {
		'sections':db_tools.exec_action(dbc,'get_report_sections',[int(params['report_id'])]),
		'report_info':db_tools.exec_action(dbc,'get_report_info',[int(params['report_id'])])[0]
	}
	page.setup = {
		'breadcrumbs':['finance',page.content['report_info']['name'].replace('&','&amp;')],
		'menu_title':'General Ledger',
		'menu':['recordexp', 'spacer', 'account', 'subledger', 'spacer', 'journal', 'editjournal', 'postjournal','spacer'] + report_menu_items,
		'content_title':page.content['report_info']['name'].replace('&','&amp;'),
		'template':'report/add_item.opt',
		'form':True
	}
	page.info = {
		'query_string':info.query_string
	}
	return page.render()
		
def add_item(req,**params):
	"""actually adds a line item to one of the financial reports -- redirects to index page"""
	try:
		session = Session.Session(req)
		check_access(req,session,req.uri)
		conn = get_connection(session)
		dbc = conn.cursor()
		report = {
			'sections':db_tools.exec_action(dbc,'get_report_sections',[int(params['report_id'])]),
			'report_info':db_tools.exec_action(dbc,'get_report_info',[int(params['report_id'])])[0]
		}
		if report['sections']:
			insert_position = db_tools.exec_action(dbc,'get_insert_position1',[params['report_id'],params['section_id']])[0]['order_num']
			db_tools.exec_action(dbc,'update_order_num',[insert_position,params['report_id']])
			db_tools.exec_action(dbc,'insert_new_item',[params['report_id'],params['section_id'],params['item_name'],params['account_range'].strip(),report['report_info']['default_formula_id'],(insert_position+1)])
		else:  
			insert_position = db_tools.exec_action(dbc,'get_insert_position2',[params['report_id']])[0]['order_num']
			insert_position = insert_position and insert_position or 0
			db_tools.exec_action(dbc,'insert_new_item',[params['report_id'],'null',params['item_name'],params['account_range'].strip(),report['report_info']['default_formula_id'],(insert_position+1)])
		conn.commit()
	except GeneralBusinessErr,e:
		broadcast_message = e.getErrMsg()
	except Exception,e: 
		errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
		broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
	except:
		broadcast_message = 'An undefined error occurred'
	finally:
		util.redirect(req,'/bin/report/create_report.py?report_id=%s'%params['report_id'])
		
def save_change(req,**params):
	"""actually updates the account ranges for the current report -- redirects to index page"""
	try:		
		session = Session.Session(req)
		check_access(req,session,req.uri)
		conn = get_connection(session)		
		changed_items=params['changed_items'][:-1]
		for item in changed_items.split(';'):
			db_tools.exec_action(conn.cursor(),'update_params',[params[item],item])
		conn.commit()
	except GeneralBusinessErr,e:
		broadcast_message = e.getErrMsg()
	except Exception,e: 
		errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
		broadcast_message = errmsg.replace('<','').replace('>','').replace('.__str__','')
	except:
		broadcast_message = 'An undefined error occurred'
	finally:
		util.redirect(req,'/bin/report/create_report.py?report_id=%s'%params['report_id'])
		
def report(req,**params):
	"""actually runs the report, saves the results and displays them in printer-friendly format"""
	page = Page(req, company_db=True)
	dbc = page.company_db.cursor()
	page.content = {
		'report_info':db_tools.exec_action(dbc,'get_report_info',[int(params['report_id'])])[0]
	}
	db_tools.exec_action(dbc,'del_report_preresult',[params['report_id']])
	section_str = ''
	for item in db_tools.exec_action(dbc,'get_item_info1',[params['report_id']]):
		ac_range_condition_parts = ['(id >= %s AND id <= %s)' % (ac_range.split('-')[0].strip(), ac_range.split('-')[-1].strip()) for ac_range in item['params'].split(',')]
		condition =  'WHERE ' + ' OR '.join(ac_range_condition_parts)
		sql = content['report_info']['isincl_date'] and item['formula'] % (params['date_start'] ,params['date_end'], condition) or item['formula'] % condition
		dbc.execute(sql)
		sumamount = dbc.fetchall()[0][0]
		if sumamount:
			db_tools.exec_action(dbc,'insert_result',[item['report_id'],item['id'],sumamount])
			if item['section_id']: section_str = section_str + str(item['section_id']) + ','
	for item in db_tools.exec_action(dbc,'get_item_info2',[params['report_id']]):
		sql=item['formula']
		dbc.execute(sql)
		sumamount = dbc.fetchall()[0][0]
		if sumamount: db_tools.exec_action(dbc,'insert_result',[item['report_id'],item['id'],sumamount])
	section_str = section_str and section_str[:-1] or '-1'
	for item in db_tools.exec_action(dbc,'get_item_info0',[params['report_id'],section_str]): db_tools.exec_action(dbc,'insert_result',[item['report_id'],item['id'],'null'])
	page.company_db.commit()
	page.content['display_report'] = db_tools.exec_action(dbc,'display_report',[params['report_id']])
	report_menu_items = [params['report_id']==str(key) and value or value[:-1] for key,value in {1:'balsheet!',2:'pl!',3:'taxreport!'}.iteritems()]
	page.setup = {
		'breadcrumbs':['finance',page.content['report_info']['name'].replace('&','&amp;')],
		'menu_title':'General Ledger',
		'menu':['recordexp', 'spacer', 'account', 'subledger', 'spacer', 'journal', 'editjournal', 'postjournal','spacer'] + report_menu_items,
		'content_title':page.content['report_info']['name'].replace('&','&amp;'),
		'template':'report/print_report.opt',
		'form':True
	}
	page.info = {
		'query_string':info.query_string,
	}
	return page.render()
